/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Apoiar;

import DAO.Usuario.HibernateUtil;
import Model.Post;
import Model.Apoiar;
import Model.DetalhesPost;
import com.google.gson.Gson;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.Session;

/**
 *
 * @author pedro
 */
@Path("/apoiarUsuario")
public class ApoiarUsuario {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public Response getCoordenates(Apoiar apoiar) {
        String resultado;
        Gson gs= new Gson();
        Session session = null;
        DetalhesPost dp = new DetalhesPost();

        try {
            session = HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            ArrayList<Post> lista = (ArrayList<Post>) session.createQuery("FROM Apoiar A WHERE A.codPost =? AND A.codUsuario=?")
                    .setInteger(0, apoiar.getCodPost())
                    .setInteger(1, apoiar.getCodUsuario())
                    .list();
            
            ArrayList<Long> lista2 = (ArrayList<Long>) session.createQuery("SELECT count(cod) FROM Apoiar A WHERE A.codPost =? ")
                    .setInteger(0,apoiar.getCodPost())
                    .list();

            HibernateUtil.commitTransaction();
            if (!lista2.isEmpty()) { 
                dp.setQtdeApoios( lista2.get(0));
            }
            else {
                dp.setQtdeApoios(0);
            }

            if (!lista.isEmpty()) {
                dp.setApoiou(1);
            } else {
                dp.setApoiou(0);
            }
            
            resultado=gs.toJson(dp);
          
            
        } catch (Exception e) {
            System.out.println(e);
            resultado = "Error";
            session.getTransaction().rollback();
        } finally {
            try {
                HibernateUtil.closeSession();
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }

        return Response.status(201).entity(resultado).build();
    }
}
